const app = getApp();
const common = require('../../utils/common.js');
const api = require('../../config/api.js');

var WxParse = require('../../lib/wxParse/wxParse.js');

Page({
  data: {
    imgUrl: app.globalData.imgurl,
    tuangouId: '',
    givePoint: '',
    values: [],
    selectedProductStockId: '',
    cartCounts: 0,
    product: null,
    productStock: null,
    couponTypeList: [],
    isSell: false,
    sellDate: '',
    isSpec: 0,
    specNameValue: [],
    productStockId: '',
    id: 0,
    goods: {},
    gallery: [],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    openCoupons:false,
    openDetail: false,
    bottomBtn: true,
	  openShare: false,
    openToshare: false,
    boxShow: false,
    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png",
    isTip: 0,
    isCollect: false
  },
  onLoad: function (options) {
    this.setData({
      productStockId: options.productSkuId
    });
  },
  onShow: function () {
    app.globalData.checkedAddress = null
    this.getProductInfo();
  },
  tel: function () {
    wx.makePhoneCall({
      phoneNumber: app.globalData.phoneNumber,
    })
  },
  //收藏
  collect: function () {
    var that = this;
    var memberId = wx.getStorageSync("memberId");
    if (!memberId) {
      wx.navigateTo({
        url: '/pages/shouquan/shouquan'
      })
    } else {
      that.setData({
        isCollect: !that.data.isCollect
      });
      var data = {
        isCollect: that.data.isCollect,
        productId: that.data.product.id,
        productStockId: that.data.productStock.id
      }
      common.request(api.ProductCollect, data, 'post').then(function (data) {
        if (data.type === 'success') {
          common.showSuccessToast(data.content);
        } else {
          common.showErrorToast(data.content);
        }
      });
    }
  },
  //回到首页
  goIndex: function () {
    wx.switchTab({
      url: '/pages/index2/index2',
    })
  },
  //商品信息
  getProductInfo: function () {
    let that = this;
    let data = {
      productStockId: that.data.productStockId
    }
    common.request(api.ProductInfo, data, 'post').then(function (data) {
      if (data.type === 'success') {
        app.globalData.zhekou = data.data.zhekou
        that.setData({
          product: data.data.product,
          productStock: data.data.productStock,
          productImageList: data.data.productImageList,
          specNameValue: data.data.specNameValue,
          isCollect: data.data.isCollect,
          zhekou:data.data.zhekou
        });
        WxParse.wxParse('content', 'html', data.data.product.content, that, 0);
      }
    });
  },
  //减少数量
  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  //增加数量
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },
  //直接购买或添加至购物车
  addCartOrBuy: function (event) {
    var that = this;
    var clickType = event.currentTarget.dataset.name;
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    } else {
			if (!wx.getStorageSync("memberId")) {
				wx.navigateTo({
					url: '/pages/shouquan/shouquan'
				});
			} else {
				// common.request(api.CheckImproveUrl, {}, 'POST').then(function (data) {
				// 	if (data.type == 'success') {
				// 		var isImprove = data.data.isImprove;
				// 		if (isImprove == 0) {
				// 			wx.navigateTo({
				// 				url: '/pages/ucenter/improveinfo/improveinfo',
				// 			})
				// 		} else {
							if (!that.isCheckedAllSpec()) {
								common.showErrorToast('请选择规格');
								return false;
							}
								var data = {
									productStockId: that.data.productStock.id,
									quantity: that.data.number
								}
								if (clickType == 'cart') {
									common.request(api.CartAdd, data, "POST").then(function (data) {
										if (data.type == 'success') {
											common.showSuccessToast('添加成功');
											setTimeout(function () {
												that.setData({
													openAttr: !that.data.openAttr,
													boxShow: !that.data.boxShow,
													cartCounts: data.data.cartCounts
												});
											}, app.globalData.showLodingTime);
										} else {
											common.showErrorToast(data.content);
										}
									});
								} else if (clickType == 'buy') {
									common.request(api.CartAddBuy, data, "POST").then(function (data) {
										if (data.type == 'success') {
											app.globalData.checkedGoods = data.data.checkedGoods;
											app.globalData.goodsTotalPrice = data.data.goodsTotalPrice;

											wx.navigateTo({
												url: '../shopping/checkout/checkout?good_type=' + that.data.product.pdtAttr + "&zhekou=" + that.data.zhekou + "&payType=" + that.data.productStock.payType
											})
										} else {
											common.showErrorToast(data.content);
										}
									});
								}
				// 		}
				// 	}
				// });
			}
    }
  },
  //选择规格
  switchAttrPop: function () {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    }
  },
  //规格值选择事件
  clickSkuValue: function (event) {
    let that = this;
    let specNameValue = that.data.specNameValue;
    let specNameId = event.currentTarget.dataset.nameId;
    let specValueId = event.currentTarget.dataset.valueId;
    let specNameIndex = event.currentTarget.dataset.nameIndex;
    let specValueIndex = event.currentTarget.dataset.valueIndex;
    for (let i = 0; i < specNameValue[specNameIndex].specValue.length; i++) {
      specNameValue[specNameIndex].specValue[i].selected = false;
    }
    specNameValue[specNameIndex].specValue[specValueIndex].selected = true;
    this.setData({
      specNameValue: specNameValue
    });
    var isSelected = this.isCheckedAllSpec();
    if (isSelected) {
      var data = {
        values: this.data.values,
        productId: this.data.product.id
      }
      common.request(api.QueryProductStock, data, 'POST').then(function (data) {
        if (data.type == 'success') {
          var isTip = 0;
          var stock = data.data.productStock.stock;
          if (stock == 0) {
            isTip = 1;
          }
          var isDisabled = data.data.productStock.isDisabled;
          if (isDisabled == 1) {
            isTip = 2;
          }
          that.setData({
            productStock: data.data.productStock,
            isTip: isTip
          })
        }
      });
    }
  },
  //判断是否选择完所有规格
  isCheckedAllSpec: function () {
    let specNameValue = this.data.specNameValue;
    let index = 0;
    let values = [];
    for (let i = 0; i < specNameValue.length; i++) {
      for (let j = 0; j < specNameValue[i].specValue.length; j++) {
        let isSelected = specNameValue[i].specValue[j].selected;
        if (isSelected) {
          index ++;
          values.push(specNameValue[i].specValue[j].value);
        }
      }
    }
    this.setData({
      values: values
    });
    return index == specNameValue.length;
  },
  //关闭弹窗
  closeAttr: function () {
    this.setData({
      openAttr: false,
      boxShow: false,
    });
  },
  //分享
  onShareAppMessage: function () {
    var that = this;
    var productId = that.data.productId;
    return {
      title: '瓯客会',
      desc: '瓯客会',
      path: '/pages/goods/goods?productSkuId=' + productSkuId
    }
  }
})